/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

// let p1 = new Promise((resolve, reject) => {
//     resolve('成功')
//     reject('失败')
// })
// 定义Promise状态
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败

class MyPromise {
    // 定义构造器
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }
    }

    // promise状态
    status = PENDING
    // 执行结果
    value = undefined
    reason = undefined
    // 回调
    successCallback = []
    failCallback = []

    // 执行成功
    resolve(value) {
        // 判定状态
        if (this.status !== PENDING) return
        // 修改状态
        this.status = FULFILLED
        // 保存结果
        this.value = value
        // 回调的判断与执行
        while (this.successCallback.length) this.successCallback.shift()()
    }
    reject(reason) {
        // 流程与resolve一致
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        while (this.failCallback.length) this.failCallback.shift()()
    }
    // 回调函数
    then(successCallback, failCallback) {
        // 判断是否有对应回调参数，没有则直接返回原值
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => { throw reason }
        // 回调函数主体
        let backPromise = new ProgressEvent((resolve, reject) => {
            // 判断状态
            if (this.status === FULFILLED) {
                // 回调
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value)
                        // 判断X的类型，值还是promise对象。值直接返回，对象则根据对象返回结果决定调用
                        resolvePromise(backPromise, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason)
                        resolvePromise(backPromise, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else {
                // 等待状态处理
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value)
                            resolvePromise(backPromise, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                })
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason)
                            resolvePromise(backPromise, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                })
            }
            // 返回
            return backPromise
        })
    }
    // 主返回
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value
        return new Promise(resolve => resolve(value))
    }
}

function resolvePromise(backPromise, x, resolve, reject) {
    if (backPromise === x) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject)
    } else {
        resolve(x)
    }
}

// 导出
module.exports = MyPromise